<?php
/**
 * 健保项目接口
 */

namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use App\Services\IdEncryptService;
use CategoryRepository;
use TestingConfig;
use TestingDetailService;
use UserRecordService;
use ResultTypeService;
use ResultAttributeService;
use TestingItemService;
use TestingDeveloperService;
use TestingXjbAlgoHelper;
use TestingXjbHelper;
use XjbUserRecordService;
use App\Models\LogHelper;
class HealthController extends Controller
{

    /**返回测评列表
     * @return array
     */
    public function testingList(){
        $dev_code = TestingConfig::getValue('parter.xjb.display_dev_code');
        $dataCode = array('union_code'=>$dev_code,'enable'=>1);
        $unionCode = TestingDeveloperService::checkUnionCode($dataCode);
        $list = TestingDetailService::getList($unionCode['union_code']);
        $data['list'] = [];
        if($list){
            foreach ($list as $key => &$val){
                //加密id
                $id = IdEncryptService::encryption($val->id,'encode');
                $val['tid'] = $id;
                $val['icon']= TestingConfig::getValue('website_url').'/upload/'.$val['icon'];
                unset($val['id']);
                array_push($data['list'],$val);
            }
        }else{
            return apiError();
        }
        return apiSuccess($data);
    }

    /**控制跳转
     * @param $tid
     * @param $type
     * @return array
     */
    public function TestingDetail($type,$tid,$uid){
        if($tid && $uid && $type){
            //获取tid,解密
            $detial_id = IdEncryptService::encryption($tid,'decode');
            $tid = $detial_id[0];
            //获取uid,解密
            //$uid =  IdEncryptService::encryption($uid,'decode');
            //$uid = $uid[0];
            //校验是否已经答过
            $result = XjbUserRecordService::getByUid($uid,$tid);
            if($type=='retry' && $result){//显示题
                $data = $this -> testingItem($tid);
            }elseif(is_null($result)){//显示题
                $data = $this -> testingItem($tid);
            }else {//显示结果
                $data = $this->testingResult($uid, $tid);
            }
            return apiSuccess($data);
        }else{
            return apiError();
        }
    }

    /**根据用户uid和测评的id返回测评结果接口
     * @param $uid
     * @param $tid
     * @return array
     */
    public function testingResult($uid,$tid){
        $data = [];
        $result = XjbUserRecordService::getByUid($uid,$tid);
        if($result){
            $data['score']=$result['score'];
            $data['avg_score']=TestingXjbHelper::avgScore($tid,$result['answers']);
            $data['result']=$result['conclusion'];
            $data['description']=$this->testingDescription($tid);
            $data['extra'] = $result['extra'];
            $typeFourExpress = TestingItemService::typeFourItem($tid);
            $typeFourExpress = empty($typeFourExpress) ? null : $typeFourExpress;
            $answerArr = TestingXjbHelper::strToArr($result['answers']);
            $data['factor']= TestingXjbHelper::getFactor($answerArr,$tid,$typeFourExpress,$result['score'],$result['final_answers']);
            $data['route']=false;
            return $data;
        }else{
            return apiError();
        }

    }

    /**获取癌症描述
     * @param $tid
     */
    public function testingDescription($tid){
        $result = TestingDetailService::getById($tid);
        return $result['gist'];
    }

    /**返回测评概率值
     * @param $tid
     * @param $score
     * @param $answerstr
     * @return null
     */
    public function testingProbability($tid,$score,$answerstr){
        $detail = TestingDetailService::getById($tid);
        if($detail) {
            $result_type_id_arr = explode(',', $detail['result_type']);
            $result = ResultTypeService::result($tid,$result_type_id_arr,$score);
            $answers =TestingXjbHelper::strToArr($answerstr);
            foreach($answers as $k => $v){
                if($tid == 4 && $v['weight'] == 0 && $v['index'] == 1){
                    $result['title']="无风险";
                }
            }
            $result['score']=TestingXjbHelper::conclusion($tid,$result['factor_str'],$answers,$score);
            unset($result['factor_str']);
            return $result;
        }else{
            return null;
        }
    }



    /**根据测评id返回题目列表
     * @param $detial_id
     * @return mixed
     */
    public function testingItem($detial_id){
        $result =  TestingDetailService::getItem($detial_id);
        if($result){
            $guide=TestingDetailService::getById($detial_id);
            $result['guide']=['note'=>$guide['note'],'time'=>$guide['time'],'gist'=>$guide['gist']];
            return $result;
        }else{
            return apiError();
        }

    }

    /**改善提交
     * @param Request $request
     * @return array
     */
    public function reSubmit(Request $request){
        $uid = $request->input('uid');
        $tidencode = $request->input('tid');
        $tidArr = IdEncryptService::encryption($tidencode,'decode');
        $tid = $tidArr[0];
        $answerAgain = $request->input('answerAgain');
        $result = XjbUserRecordService::getByUid($uid,$tid);
        if($result){
            $typeFourExpress = TestingItemService::typeFourItem($tid);
            $typeFourExpress = empty($typeFourExpress) ? null : $typeFourExpress;
            $score = TestingXjbHelper::retesting($result['answers'],$tid,$typeFourExpress,$answerAgain);
            $betterScore = array('betterScore'=>$score);
            return apiSuccess($betterScore);
        }else{
            return apiError();
        }
    }

    /**提交测试题目
     * @param Request $request
     * @return array
     */
    public function submitTesting(Request $request){
        $uid = $request->input('uid');
        $tid = $request->input('tid');
        $answers = $request->input('answers');
       //LogHelper::log($answers,'xjb');
        $extra =  $request->input('extra');
        if($uid && $tid && $answers){
            //$uid = IdEncryptService::encryption($uid,'decode');
            $tid = IdEncryptService::encryption($tid,'decode');
            $data['answers'] = $answers;
            $data['uid'] = $uid;
            $data['tid'] = $tid[0];
            $data['extra'] = $extra;
            $typeFourExpress = TestingItemService::typeFourItem($data['tid']);
            $typeFourExpress = empty($typeFourExpress) ? null : $typeFourExpress;
            $reslut = TestingXjbAlgoHelper::calculate($data['tid'],$data['answers'],$typeFourExpress);
            $data['final_answers']=$reslut['finalAnswerStr'];
            $Probability=$this -> testingProbability($data['tid'],$reslut['totalScore'],$reslut['finalAnswerStr']);
            $data['score']=$Probability['score']*100;
            $data['conclusion'] =$Probability['title'];
            $reslut = XjbUserRecordService::stroeResult($data);
            if($reslut){
                $update = TestingDetailService::updataTestTimes($data['tid']);
                if($update){
                    return apiSuccess();
                }else{
                    return apiError();
                }
            }else{
                return apiError();
            }
        }else{
            return apiFailed();
        }

    }


}
